package com.example.upload.service.impl;

import com.example.upload.dto.ExecShellParamDTO;
import com.example.upload.service.UploadFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author admin
 */
@Service
@Slf4j
public class UploadFileServiceImpl implements UploadFileService {
    @Override
    public String saveFile(MultipartFile file) {
        //选择了文件，开始上传操作
        try {
            //构建上传目标路径，找到了项目的target的classes目录
            File destFile = new File(ResourceUtils.getURL("classpath:").getPath());
            if (!destFile.exists()) {


                destFile = new File("");
            }
            //输出目标文件的绝对路径
            log.info("file path:{}", destFile.getAbsolutePath());
            //拼接子路径
            SimpleDateFormat sf_ = new SimpleDateFormat("yyyyMMddHHmmss");
            String times = sf_.format(new Date());
            File upload = new File(destFile.getAbsolutePath(), "picture/" + times);
            //若目标文件夹不存在，则创建
            if (!upload.exists()) {
                boolean mkdirsRes = upload.mkdirs();
                if (!mkdirsRes) {
                    return "文件上传失败，请稍后重试！";
                }
            }
            log.info("完整的上传路径:{}/{}", upload.getAbsolutePath(), file.getOriginalFilename());
            //根据srcFile大小，准备一个字节数组
            byte[] bytes = file.getBytes();
            //拼接上传路径
            //Path path = Paths.get(UPLOAD_FOLDER + srcFile.getOriginalFilename());
            //通过项目路径，拼接上传路径
            Path path = Paths.get(upload.getAbsolutePath() + "/" + file.getOriginalFilename());
            // 开始将源文件写入目标地址
            Files.write(path, bytes);
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            // 获得文件原始名称
            String fileName = file.getOriginalFilename();
            // 获得文件后缀名称
            String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
            // 生成最新的uuid文件名称
            String newFileName = uuid + "." + suffixName;
            return "文件上传成功" + newFileName;
        } catch (IOException e) {
            log.error("文件上传失败", e);
            return e.getMessage();
        }
    }

    @Override
    public String execShell(ExecShellParamDTO paramDTO) {
        String cmd = paramDTO.getSoftPath()
                .concat(String.valueOf(paramDTO.getThreadNum()))
                .concat(" --cv=")
                .concat(String.valueOf(paramDTO.getNum()))
                .concat(paramDTO.getConfigFilePath())
                .concat(String.valueOf(paramDTO.getNum()))
                .concat(paramDTO.getLogPath());
        BufferedReader br = null;
        try {
            Process p = Runtime.getRuntime().exec(cmd);
            br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("/n/r");
            }
            log.info("sb:{}", sb.toString());

        } catch (IOException e) {
            log.error("脚本执行失败", e);
        }
        return br == null ? null : br.toString();
    }

}
